package pl.andrzejag.seleniumtests;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class SeleniumBaseUni {
	public WebDriver driver;
	public String baseUrl = "http://code.google.com";
	private StringBuffer verificationErrors = new StringBuffer();

	@Before
	public void setUp() throws Exception {
		driver = new FirefoxDriver();
		// driver = new HtmlUnitDriver();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		driver.get(baseUrl);
	}

	@After
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	public void assertTextPresent(String text) {
		assertTrue(driver.getPageSource().contains(text));
	}

	public void insertText(By by, String text) {
		driver.findElement(by).clear();
		driver.findElement(by).sendKeys(text);
	}

	public void click(By by) {
		driver.findElement(by).click();
	}

	public void iterateMenu(String xPath) {
		List<WebElement> meni = driver.findElements(By.xpath(xPath));
		List<String> urls = new LinkedList<String>();

		for (WebElement webElement : meni) {
			urls.add(webElement.getAttribute("href").toString());
		}

		for (String url : urls) {
			driver.get(url);
			Actions action = new Actions(driver);
			// action.keyDown(Keys.ARROW_DOWN);
		}
	}
	
	public void iterateMenuByXpath(String path) {
		List<WebElement> menu = driver.findElements(By.xpath(path));
		for (int i = 1; i < menu.size(); i++) {
			click(By.xpath(path + "[" + i + "]"));
		}
	}
	
	public void iterateMenuBy() {
		List<WebElement> menu_i = driver.findElements(By.xpath("//html/body/div[4]/div[3]/ul/"));
		for (int i = 1; i < menu_i.size(); i++) {
			List<WebElement> menu_j = driver.findElements(By.xpath("//html/body/div[4]/div[3]/ul/li["+i+"]/div/ul/"));
			for (int j = 1; j < menu_j.size(); j++) {
				click(By.xpath("//html/body/div[4]/div[3]/ul/li["+i+"]/div/ul/li/["+j+"]/a"));
			}
		}
	}

	public boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
}
